import 'package:aichat_flutter_wallet/module/module_browser/provider/browser_proviser.dart';
import 'package:aichat_flutter_wallet/module/module_news/provider/news_provider.dart';

import 'package:aichat_flutter_wallet/module/module_trade/provider/trans_provider.dart';

import 'package:aichat_flutter_wallet/module/module_wallet/provider/wallet_index_provider.dart';

import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';

import 'package:aichat_flutter_wallet/module_common/router/app_route_page_utils.dart';

import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:lib_database/lib_database.dart';

import 'package:lib_database/objectbox.dart';

import 'app_config.dart';
import 'module/module_dapp/provider/dapp_cache_provider.dart';

import 'module/module_dapp/provider/dapp_page_provider.dart';

import 'module/module_dapp/provider/dapp_provider.dart';

import 'module/module_wallet/provider/wallet_assets_provider.dart';
import 'module/module_wallet/provider/wallet_node_provider.dart';

import 'module_common/network/http_configuration.dart';

import 'module_common/provider/token_info_provider.dart';

import 'module_common/provider/token_list_provider.dart';

import 'module_common/provider/user_settings_provider.dart';

import 'module_common/provider/wallect_connect_provider.dart';
import 'module_common/provider/wallet_info_provider.dart';

import 'module_common/router/routers.dart';

// --------------   多语言 模块  --------------------------

import 'package:lib_language/lib_language.dart';

// --------------  数据 存储 -----------------------

import 'package:lib_database/sp.dart';

import 'package:provider/provider.dart';

import 'package:aichat_flutter_wallet/module_common/provider/theme_model.dart';

//  --------------------------------------------------

import 'module_common/config/Config.dart';

import './module_common/provider/nav_key.dart';

import 'package:fluro/fluro.dart';
import 'kai_print.dart';

void main(List<String>? args) async {
  WidgetsFlutterBinding.ensureInitialized();
  NativeChannelBridge().init();
  // 创建对象盒子
  await ScreenUtil.ensureScreenSize();
  await EasyLocalization.ensureInitialized();
  // 初始化 数据库
  await SP().init();
  await initDataBase(args);
  //  正式 环境 关闭 isDev
  await httpInit(args,isDev:true);
  // rootPageType = RootPageType.BaseInit;


  runApp(MultiProvider(
      providers: [
        ChangeNotifierProvider<ThemeProvider>(create: (_) => ThemeProvider()),
        ChangeNotifierProvider<WalletIndexProvider>(
            create: (_) => WalletIndexProvider()),
        ChangeNotifierProvider<WalletAssetsProvider>(
            create: (_) => WalletAssetsProvider()),
        ChangeNotifierProvider<BrowserProvider>(
            create: (_) => BrowserProvider()),
        ChangeNotifierProvider(create: (_) => TokenListNotifier()),
        ChangeNotifierProvider(
            create: (_) => WalletInfoNotifier(
                  _.read<TokenListNotifier>(),
                )),
        ChangeNotifierProvider(
          create: (_) => TokenInfoNotifier(),
        ),
        ChangeNotifierProvider(create: (_) => DAppProvider()),
        ChangeNotifierProvider(create: (_) => DAppPageProvider()),
        ChangeNotifierProvider(create: (_) => DAppCacheProvider()),
        ChangeNotifierProvider(create: (_) => UserSettingsProvider()),
        ChangeNotifierProvider(create: (_) => NodeProvider()),
        ChangeNotifierProvider(create: (_) => TransactionProvider()),
        // 咨询provider
        ChangeNotifierProvider(create: (_) => NewsProvider()),
        ChangeNotifierProvider(create: (_) => WCProviderNotifier()),
      ],
      child: EasyLocalization(
          supportedLocales: supportedLocales,
          path: 'assets/translations',
          fallbackLocale: const Locale('en'),
          child: new AppConfig(
            appName: 'Kai',
            flavorName: 'production',
            apiBaseUrl: 'https://dev-api.example.com/',
            child: const MainApp(),
          ))));

  // child: const iOSTestPage())));
}

//网络请求配置

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    var config = AppConfig.of(context);
    final router = FluroRouter();
    Routes.configureRoutes(router);
    Routes.router = router;
    final themeProvider = Provider.of<ThemeProvider>(context, listen: false);

    return ScreenUtilInit(
      designSize: Size(375, 674),
      minTextAdapt: true,
      builder: (context, child) {
        return MaterialApp(
          title: config!.appName,

          locale: context.locale,

          navigatorKey: NavKey.navKey,

          debugShowCheckedModeBanner: false,

          localizationsDelegates: context.localizationDelegates,

          supportedLocales: context.supportedLocales,

          theme: themeProvider.getThemeData(isDark: false),

          darkTheme: themeProvider.getThemeData(isDark: true),

          themeMode: themeProvider.getThemeMode(themeProvider.themeMode),

          initialRoute: Routes.rootRoute,
          // initialRoute: Routes.news_detail,

          onGenerateRoute: Routes.router?.generator,

          navigatorObservers: [
            AppRouterPageUtils().routeObserver
          ], //添加路由变化的页面事件监听

          // builder: FToastBuilder(),

          // home: const NavigationHomeScreen(),
        );
      },
    );
  }
}

Future<void> initDataBase(List<String>? args) async {
  //此数据库逻辑可应用于多引擎访问数据库

  if (args == null || args.length < 2) {
    //没有创建过数据库，那就要创建数据库

    // 初始化 数据库

    var store = await ObjectBox().create();

    //把数据库传给原生通道，再由原生通道给另一个flutter引擎


    NativeChannelBridge().sendReference(store.reference);

    kaiPrint('engined end');
  } else {
    //有值，证明在其他引擎创建了数据库实例，

    var list = args[1].split(',');

    List<int> intList = [];

    list.forEach((element) {
      intList.add(int.parse(element));
    });

    ByteData byteData = ByteData.sublistView(Uint8List.fromList(intList));

    // 原生通道传过来的数据库实例，初始化 数据库

    ObjectBox().referenceStore(byteData);
  }
}
